package ase.assignment.sts.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ase.assignment.sts.api.CustomHandler;
import ase.assignment.sts.utils.ActionConfig;
import ase.assignment.sts.utils.STSConstants;

public class LoginAction extends GenericAction{
	
	public void process(HttpServletRequest request, 
			HttpServletResponse response )
		throws ServletException, IOException{
		
		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("pass");

		try{
			boolean isOk = CustomHandler.getInstance().login(username, password);

			if( isOk ){
				System.out.println("Acount valid");
				session.setAttribute(STSConstants.SESSION_USER, username);
			}


		}catch(Throwable e)
		{
			e.printStackTrace();
		}


	}

	public void forward(HttpServletRequest request, 
			HttpServletResponse response, 
			ServletContext context, 
			ActionConfig ac )
		throws ServletException, IOException{

		HttpSession session = request.getSession();
		String customname = (String)session.getAttribute(STSConstants.SESSION_USER);
		if( customname != null ){
			RequestDispatcher rd = context.getRequestDispatcher(ac.getForwardURL());
			rd.forward( request, response );
		}
		else{
			RequestDispatcher rd = context.getRequestDispatcher("/");
			rd.forward( request, response );
		}
	}


}

